import { routerRedux } from 'dva/router';
import queryString from 'query-string';
import modelExtend from 'dva-model-extend';
import { commonModel } from './common';
import * as loginService from './../services/login';
import constructMenu from './../utils/constructMenu';

export default modelExtend(commonModel,{
    namespace: 'dashboard',
    state: {
        user: {},
        permissions: {
            visit: [],
        },
        menu: [],
        hasPermissions: false,
        isCollapsed: false,
        themeStyle: 'dark',
        locationPathname: '',
        locationQuery: {},
    },
    subscriptions: {
        setupHistory ({ dispatch, history }) {
            history.listen((location) => {
                dispatch({
                    type: 'updateState',
                    payload: {
                        locationPathname: location.pathname,
                        locationQuery: queryString.parse(location.search),
                    },
                })
            })
        },
        setup ({ dispatch }) {
            dispatch({ type: 'query' });
        },
    },
    effects: {
        * query (action, { call, put, select }) {
            const taken = window.localStorage.getItem('taken');
            const { locationPathname } = yield select(_ => _.dashboard);
            if(taken === null || taken === ''){
                yield put(routerRedux.push({ pathname: '/login' }));
                return;
            }
            const { user, permissions } = yield call(loginService.query, { taken });
            if (user && permissions) {   //用户存在且已登录
                //根据用户权限生成菜单
                const { menu } = yield call(loginService.menu, { permissions });
                let temp = constructMenu(menu);
                yield put({
                    type: 'updateState',
                    payload: {
                        user,
                        permissions,
                        menu: temp,
                        hasPermissions: true
                    }
                });
                yield put(routerRedux.push({ pathname: locationPathname }));
            } else {
                yield put(routerRedux.push({
                    pathname: '/login',
                    search: queryString.stringify({
                        from: locationPathname,
                    })
                }));
            }
        },

        * logout (anction, { call, put }) {
            window.localStorage.removeItem('taken');
            const data = yield call(loginService.logout);
            if (data.success) {
                yield put({ type: 'query' })
            } else {
                throw (data)
            }
        },
    }
})